/**
 * 
 */
package com.ermax.aircond.common.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ermax.aircond.common.dao.ReadMachineDataDao;
import com.ermax.aircond.common.dao.WriteMachineDataDao;
import com.ermax.aircond.common.domain.WriteMachineData;
import com.ermax.aircond.report.domain.CommandCheck;

/**
 * @author Eric
 *
 */
@Service("writeMachineDataService")
public class WriteMachineDataService {

	private static final Logger logger = Logger.getLogger(WriteMachineDataService.class);
	
	@Resource(name="writeMachineDataDao")
	private WriteMachineDataDao writeMachineDataDao;
	@Resource(name="readMachineDataDao")
	private ReadMachineDataDao readMachineDataDao;	
	
	/* (non-Javadoc)
	 * @see com.ermax.aircond.common.service.WriteMachineDataService#insert(com.ermax.aircond.common.domain.WriteMachineData)
	 */
	@Transactional
	public int insert(WriteMachineData writeMachineData) {
		// TODO Auto-generated method stub
		logger.debug("Insert!");
		writeMachineDataDao.insert(writeMachineData);
		
		return 0;
	}

	@Transactional(readOnly = true)
	public WriteMachineData select(short nid) {
		return writeMachineDataDao.select(nid);
	}

	public void insertUpdate(WriteMachineData writeMachineData) {
		logger.debug("Insert Update!");
		
		WriteMachineData updateData = select(writeMachineData.getNid());
		
		if (null == updateData) {		
			insert(writeMachineData);
		} else {
			updateData.setCmd(writeMachineData.getCmd());			
			update(updateData);
		}		

	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void setCommand(WriteMachineData writeMachineData) {
		writeMachineDataDao.setCommand(writeMachineData);
		
	}
	
	@Transactional
	public void update(WriteMachineData writeMachineData) {
		logger.debug("Update!");
		writeMachineDataDao.update(writeMachineData);
		readMachineDataDao.updateRcmd(writeMachineData.getNid());
	}
	
	@Transactional
	public void updateStatus() {		
		
		writeMachineDataDao.updateStatus();

	}
	
	@Transactional
	public void delete(WriteMachineData writeMachineData) {		
		
		writeMachineDataDao.delete(writeMachineData);

	}
	
	public void flush(){
		writeMachineDataDao.flush();
	}
	
	public List<CommandCheck> findLatestMachineData() {
		return writeMachineDataDao.findLatestMachineData();
	}
}
